package edu.whu.puppygo.service.Impl;

import edu.whu.puppygo.config.OssConfig;
import edu.whu.puppygo.dao.PetDao;
import edu.whu.puppygo.dao.PetRecordDao;
import edu.whu.puppygo.dao.UserDao;
import edu.whu.puppygo.entity.Pet;
import edu.whu.puppygo.entity.PetRecord;
import edu.whu.puppygo.entity.User;
import edu.whu.puppygo.exception.BackendException;
import edu.whu.puppygo.service.PetService;
import edu.whu.puppygo.util.FileUtil;
import edu.whu.puppygo.util.GlobalUser;
import edu.whu.puppygo.util.OssUtil;
import edu.whu.puppygo.vo.PetVo;
import edu.whu.puppygo.vo.UpdateAvatorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;


/**
 * @Author xinjiezhuang
 * @Date 2023-11-20
 */
@Service
public class PetServiceImpl implements PetService {

    @Autowired
    private PetDao petDao;

    @Autowired
    private PetRecordDao petRecordDao;

    @Resource
    private OssUtil ossUtil;

    @Resource
    private UserDao userDao;

    /**
     * 更新宠物头像
     */
    @Override
    public UpdateAvatorVo updatePetAvatarWithFile(Long petId, MultipartFile mpfile) {
        User globalUser = GlobalUser.getUser();
        UpdateAvatorVo updateAvatorVo = new UpdateAvatorVo();
        // 从MultipartFile中获取文件名
        String originalFileName = mpfile.getOriginalFilename();
        originalFileName = FileUtil.RandomFileName(originalFileName);
        if (!mpfile.isEmpty()) {
            // 使用OssUtil上传文件到阿里云OSS，并获取上传后的文件名
            String FileName = OssConfig.getPetPicPath() + originalFileName;
            String uploadedFileName = ossUtil.uploadFile(mpfile, FileName);
            updateAvatorVo.setAvator(OssConfig.getFullUrl() + FileName);
        }
        updatePetAvatar(petId, updateAvatorVo.getAvator());
        return updateAvatorVo;
    }

    public Pet updatePetAvatar(long petId, String picture) {
        Optional<Pet> optionalPet = petDao.findById(petId);
        if (optionalPet.isPresent()) {
            Pet pet = optionalPet.get();
            pet.setPicture(picture);
            return petDao.save(pet);
        } else {
            // 处理找不到宠物的情况
            return null;
        }
    }


    @Override
    public Pet createPetWithPicture(Pet pet, MultipartFile mpfile) {
        User globalUser = GlobalUser.getUser();
        pet.setUserId(globalUser.getId());
        if (!mpfile.isEmpty()) {
            String originalFileName = mpfile.getOriginalFilename();
            originalFileName = FileUtil.RandomFileName(originalFileName);
            String fileName = OssConfig.getPetPicPath() + originalFileName;
            String uploadedFileName = ossUtil.uploadFile(mpfile, fileName);
            pet.setPicture(OssConfig.getFullUrl() + uploadedFileName);
        }
        Pet createdPet = createPet(pet);
        List<Pet> petList = getAllPetsByUserId(globalUser.getId());
        if (petList.isEmpty()) {
            globalUser.setMainPetId(pet.getId());
        }
        petList.add(createdPet);


        return createdPet;
    }

    @Override
    public PetVo getPetVo(long userId) {
        PetVo petVo = new PetVo();
        List<Pet> petList = getAllPetsByUserId(userId);
        petVo.setPets(petList);
        return petVo;
    }


    /**
     * 根据用户ID获取所有宠物
     */
    @Override
    public List<Pet> getAllPetsByUserId(Long userId) {
        return petDao.findByUserId(userId);
    }


    @Override
    public Optional<Pet> getPetById(long petId) {
        return petDao.findById(petId);
    }

    @Override
    public Pet createPet(Pet pet) {
        return petDao.save(pet);
    }

    @Override
    public void deletePet(long petId) {
        petDao.deleteById(petId);
    }

    /**
     * 更新宠物的时候如果体重发生变化，要创建并保存PetRecord对象，然后更新Pet对象
     */
    @Override
    public Pet updatePet(Pet pet) {
        Optional<Pet> existingPetOptional = petDao.findById(pet.getId());
        if (existingPetOptional.isPresent()) {
            // 判断体重是否发生变化
            if (pet.getWeight() != null && existingPetOptional.get().getWeight() != pet.getWeight()) {
                // 体重发生变化，创建并保存 PetRecord 对象
                PetRecord petRecord = new PetRecord();
                petRecord.setWeight(pet.getWeight());
                petRecord.setPetId(existingPetOptional.get().getId());
                petRecord.setRecordTime(LocalDateTime.now());
                petRecordDao.save(petRecord);
            }
        }
        return petDao.save(pet);
    }


    /**
     * 更新宠物体重的时候要改变PetRecord和Pet的值
     */
    @Override
    public Pet updatePetWeight(long petId, String newWeight) {
        Optional<Pet> optionalPet = petDao.findById(petId);
        if (optionalPet.isPresent()) {
            Pet pet = optionalPet.get();
            // 保存原始体重，可选
            double oldWeight = Double.valueOf(pet.getWeight());
            // 更新体重
            pet.setWeight(newWeight);
            // 创建 PetRecord 对象
            PetRecord petRecord = new PetRecord();
            petRecord.setWeight(newWeight);
            petRecord.setPetId(pet.getId());
            petRecord.setRecordTime(LocalDateTime.now());
            // 保存 PetRecord
            petRecordDao.save(petRecord);
            // 更新 Pet 实体
            return petDao.save(pet);
        } else {
            // 处理找不到宠物的情况
            return null;
        }
    }

    @Override
    public List<Pet> create(Pet pet, MultipartFile mpfile) {
        User globalUser = GlobalUser.getUser();
        pet.setUserId(globalUser.getId());
        List<Pet> petList = getAllPetsByUserId(globalUser.getId());
        if (mpfile != null) {
            String originalFileName = mpfile.getOriginalFilename();
            originalFileName = FileUtil.RandomFileName(originalFileName);
            String fileName = OssConfig.getPetPicPath() + originalFileName;
            String uploadedFileName = ossUtil.uploadFile(mpfile, fileName);
            pet.setPicture(OssConfig.getFullUrl() + uploadedFileName);
        }
        Pet createdPet = createPet(pet);
        if (petList.isEmpty()) {
            globalUser.setMainPetId(pet.getId());
        }
        petList.add(createdPet);
        return petList;
    }

    @Override
    public PetVo deletePetById(String petId) {
        User globalUser = GlobalUser.getUser();
        PetVo petVo = new PetVo();
        if (!getPetById(Long.valueOf(petId)).isPresent()) {
            throw new BackendException("宠物不存在");
        }
        deletePet(Long.valueOf(petId));
        List<Pet> petList = getAllPetsByUserId(globalUser.getId());
        userDao.save(globalUser);
        petVo.setPets(petList);
        return petVo;
    }


    /**
     * 更新 Pet 实体的字段
     */
    private void updatePetFields(Pet existingPet, Pet updatedPet) {
        existingPet.setName(updatedPet.getName() != null ? updatedPet.getName() : existingPet.getName());
        existingPet.setKind(updatedPet.getKind() != null ? updatedPet.getKind() : existingPet.getKind());
        existingPet.setAge(updatedPet.getAge() >= 0 ? updatedPet.getAge() : existingPet.getAge());
        existingPet.setSex(updatedPet.getSex());
        existingPet.setWeight(Integer.valueOf(updatedPet.getWeight()) >= 0 ? updatedPet.getWeight() : existingPet.getWeight());
//        existingPet.setSterilization(updatedPet.getS());
        existingPet.setPicture(updatedPet.getPicture() != null ? updatedPet.getPicture() : existingPet.getPicture());
        existingPet.setUserId(updatedPet.getUserId());
    }
}
